import * as dayjs from 'dayjs'
import * as duration from 'dayjs/plugin/duration'
import * as isBetween from 'dayjs/plugin/isBetween'
import * as tz from 'dayjs/plugin/timezone'
import * as utc from 'dayjs/plugin/utc'
import * as weekOfYear from 'dayjs/plugin/weekOfYear'
import { isNullOrEmptyString } from './string-helper'

dayjs.extend(utc)
dayjs.extend(tz)
dayjs.extend(isBetween)
dayjs.extend(duration)
dayjs.extend(weekOfYear)

export const isValidTime = (time: string | Date | null | undefined): boolean => {
    if (time === null || time === undefined) {
        return false
    }

    if (typeof time === 'string') {
        if (isNullOrEmptyString(time)) {
            return false
        }
    }

    return parseDate(time).isValid()
}

export const getNow = () => {
    return dayjs.utc()
}

export const getNowInChina = () => {
    return dayjs().tz('Asia/Shanghai')
}

export const parseDateKeepOrigin = (d: Date | string) => {
    return dayjs(d)
}

export const parseDate = (d: Date | string) => {
    return dayjs.utc(d)
}

export const parseDateInChina = (d: Date | string) => {
    return dayjs.tz(d, 'Asia/Shanghai')
}

export const convertUTCToChina = (d: Date | string) => {
    return dayjs.utc(d).tz('Asia/Shanghai')
}

export const convertChinaToUTC = (d: Date | string) => {
    return dayjs.tz(d, 'Asia/Shanghai').utc()
}

export const getNowDayInChina = () => {
    return getNowInChina().startOf('day')
}

export const getNowMonthInChina = () => {
    return getNowInChina().startOf('month')
}

export const createTodayTime = (today: dayjs.Dayjs, time: string) => {
    const [hours, minutes, seconds] = time.split(':').map(Number)

    return today.add(hours, 'hour').add(minutes, 'minute').add(seconds, 'second')
}

export const isValidTimeFormat = (time: string): boolean => {
    // 正则表达式用于匹配格式 HH:mm:ss
    // 小时不超过 23 ，分，秒不会超过 59
    const timePattern = /^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d$/
    return timePattern.test(time)
}

export const parseUnixTime = (unixTime: number) => {
    return dayjs.unix(unixTime)
}
